package com.aw.baselib.net.callback;

import com.aw.baselib.R;
import com.aw.baselib.base.AwBaseApplication;
import com.aw.baselib.base.AwCustomResponseBean;
import com.aw.baselib.base.AwResponseBean;
import com.aw.baselib.bean.rx.EventReLoginType;
import com.aw.baselib.util.AwLog;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.functions.Consumer;

/**
 * @author : hzw
 * @date : 2021/12/10
 */
public class AwCustomRspSubscriber<T extends AwCustomResponseBean> implements Consumer<T> {

    public static final int UNKNOWN_CODE = -1;
    private AwCustomRspCallback<T> mRspCallback;

    public AwCustomRspSubscriber(AwCustomRspCallback<T> rspCallback) {
        mRspCallback = rspCallback;
    }

    @Override
    public void accept(T t)  {
        if(null == mRspCallback) {
            AwLog.d("===AwCustomRspSubscriber callback is null, return");
        } else {
            if(t == null) {
                mRspCallback.onFailure(UNKNOWN_CODE, AwBaseApplication.getInstance().getString(R.string.common_server_return_empty_data));
            } else if(t.isTokenError()) {
                EventBus.getDefault().postSticky(new EventReLoginType(null));
            } else if(t.isSuccess()) {
                mRspCallback.onSuccess(t);
            } else {
                mRspCallback.onFailure(t.getCode(), t.getMsg());
            }
            mRspCallback.onCompleted();
        }
    }
}
